package com.wuxianggujun.ide.ui;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceManager;

/**
 * @project: JvIDE
 * @author: WEG
 * @description:
 **/
public abstract class StyledUI extends AppCompatActivity {

    private SharedPreferences preferences;
    @Override
    final protected void onCreate(@Nullable Bundle savedInstanceState) {
        onUIPreCreate(savedInstanceState);
        preferences= PreferenceManager.getDefaultSharedPreferences(this);

        super.onCreate(savedInstanceState);

        if (isViewBindingEnabled()){
            if (getViewBindingRoot()!=null)
                setContentView(getViewBindingRoot());
        }else {
            if (getUILayoutId() != -1)
                setContentView(getUILayoutId());
        }
        applyThemeStyle();
        onUICreated(savedInstanceState);
    }

    private void applyThemeStyle() {
        if (isLightTheme()){
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR|View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
            setTheme(getLightThemeId());
        }else {
            setTheme(getDarkThemeId());
        }
    }

    private int getLightThemeId(){
        return isPreferencesUI()? R.style.Theme_UI_Preferences: R.style.Theme_UI;
    }

    private int getDarkThemeId(){
        return isPreferencesUI()? R.style.Theme_UI_Preferences_Dark: R.style.Theme_UI_Dark;
    }

    protected void onUIPreCreate(Bundle savedInstanceState) {

    }

    protected abstract void onUICreated(@Nullable Bundle savedInstanceState);

    @NonNull
   final protected SharedPreferences getPreferences(){
        if (preferences==null)
            preferences=PreferenceManager.getDefaultSharedPreferences(this);
        return preferences;
    }

    protected boolean isLightTheme(){
        return getPreferences().getBoolean("app_theme_light", true);
    }

    protected int getUILayoutId(){
        return -1;
    }

    protected boolean isViewBindingEnabled(){
        return true;
    }

    protected View getViewBindingRoot(){
        return null;
    }

    protected boolean isPreferencesUI(){
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        preferences=null;
    }
}
